const fs = require('fs');
const path = require('path');

// 读取文件内容并转义为字符串
function readFileAsString(filePath) {
  try {
    const content = fs.readFileSync(filePath, 'utf8');
    return JSON.stringify(content);
  } catch (error) {
    console.warn(`Warning: Could not read file ${filePath}`);
    return 'null';
  }
}

// 读取二进制文件并转换为 base64
function readFileAsBase64(filePath) {
  try {
    const content = fs.readFileSync(filePath);
    return `"data:${getMimeTypeFromPath(filePath)};base64,${content.toString('base64')}"`;
  } catch (error) {
    console.warn(`Warning: Could not read file ${filePath}`);
    return 'null';
  }
}

// 根据文件路径获取 MIME 类型
function getMimeTypeFromPath(filePath) {
  const ext = path.extname(filePath).toLowerCase();
  const mimeTypes = {
    '.html': 'text/html',
    '.css': 'text/css',
    '.js': 'text/javascript',
    '.json': 'application/json',
    '.png': 'image/png',
    '.jpg': 'image/jpeg',
    '.jpeg': 'image/jpeg',
    '.gif': 'image/gif',
    '.svg': 'image/svg+xml',
    '.ico': 'image/x-icon',
    '.woff': 'application/font-woff',
    '.woff2': 'application/font-woff2',
    '.ttf': 'application/font-ttf',
    '.eot': 'application/vnd.ms-fontobject',
    '.otf': 'application/font-otf'
  };
  return mimeTypes[ext] || 'application/octet-stream';
}

// 判断是否为二进制文件
function isBinaryFile(filePath) {
  const ext = path.extname(filePath).toLowerCase();
  const binaryExtensions = ['.png', '.jpg', '.jpeg', '.gif', '.ico', '.woff', '.woff2', '.ttf', '.eot', '.otf'];
  return binaryExtensions.includes(ext);
}

// 构建静态文件映射
function buildStaticFilesMap() {
  const staticFiles = {};

  // 添加主页
  staticFiles['/'] = readFileAsString('index.html');
  staticFiles['/index.html'] = readFileAsString('index.html');

  // 添加样式和脚本文件
  staticFiles['/home_style.css'] = readFileAsString('home_style.css');
  staticFiles['/home_script.js'] = readFileAsString('home_script.js');

  // 添加游戏文件
  const games = ['snake_game', 'fish_game'];
  games.forEach(game => {
    const gameDir = path.join(__dirname, game);
    if (fs.existsSync(gameDir)) {
      // 游戏主页
      const gameIndexPath = path.join(gameDir, 'index.html');
      if (fs.existsSync(gameIndexPath)) {
        staticFiles[`/${game}/index.html`] = readFileAsString(gameIndexPath);
        staticFiles[`/${game}/`] = readFileAsString(gameIndexPath);
      }

      // 游戏CSS和JS文件
      const gameFiles = ['style.css', 'script.js'];
      gameFiles.forEach(file => {
        const filePath = path.join(gameDir, file);
        if (fs.existsSync(filePath)) {
          staticFiles[`/${game}/${file}`] = readFileAsString(filePath);
        }
      });

      // 游戏资源文件
      const assetsDir = path.join(gameDir, 'assets');
      if (fs.existsSync(assetsDir)) {
        const assetFiles = fs.readdirSync(assetsDir, { recursive: true });
        assetFiles.forEach(file => {
          if (typeof file === 'string') {
            const fullPath = path.join(assetsDir, file);
            if (fs.statSync(fullPath).isFile()) {
              const routePath = `/${game}/assets/${file}`;
              if (isBinaryFile(fullPath)) {
                staticFiles[routePath] = readFileAsBase64(fullPath);
              } else {
                staticFiles[routePath] = readFileAsString(fullPath);
              }
            }
          }
        });
      }
    }
  });

  return staticFiles;
}

// 生成完整的 worker.js 文件
function generateWorker() {
  const staticFiles = buildStaticFilesMap();

  const workerTemplate = `// Auto-generated Cloudflare Worker
// This file is automatically generated by build-worker.js

// MIME 类型映射
const mimeTypes = {
  '.html': 'text/html',
  '.js': 'text/javascript',
  '.css': 'text/css',
  '.json': 'application/json',
  '.png': 'image/png',
  '.jpg': 'image/jpeg',
  '.jpeg': 'image/jpeg',
  '.gif': 'image/gif',
  '.svg': 'image/svg+xml',
  '.wav': 'audio/wav',
  '.mp4': 'video/mp4',
  '.woff': 'application/font-woff',
  '.woff2': 'application/font-woff2',
  '.ttf': 'application/font-ttf',
  '.eot': 'application/vnd.ms-fontobject',
  '.otf': 'application/font-otf',
  '.ico': 'image/x-icon'
};

// 获取文件扩展名
function getExtension(path) {
  const lastDot = path.lastIndexOf('.');
  return lastDot === -1 ? '' : path.slice(lastDot).toLowerCase();
}

// 获取 MIME 类型
function getMimeType(path) {
  const ext = getExtension(path);
  return mimeTypes[ext] || 'application/octet-stream';
}

// 静态文件映射
const staticFiles = ${JSON.stringify(staticFiles, null, 2)};

// 处理 base64 数据的辅助函数
function decodeBase64Response(base64String) {
  const [header, data] = base64String.split(',');
  const mimeType = header.match(/data:([^;]+)/)?.[1] || 'application/octet-stream';

  // 在 Cloudflare Workers 中，我们需要将 base64 转换为 ArrayBuffer
  const binaryString = atob(data);
  const bytes = new Uint8Array(binaryString.length);
  for (let i = 0; i < binaryString.length; i++) {
    bytes[i] = binaryString.charCodeAt(i);
  }

  return new Response(bytes, {
    headers: { 'Content-Type': mimeType }
  });
}

export default {
  async fetch(request, env, ctx) {
    const url = new URL(request.url);
    let pathname = url.pathname;

    // 处理根路径
    if (pathname === '/') {
      pathname = '/';
    }

    // 处理游戏路径的 index.html 默认
    if (pathname.endsWith('/') && pathname !== '/') {
      pathname = pathname + 'index.html';
    }

    try {
      // 检查静态文件映射
      if (staticFiles[pathname]) {
        const content = staticFiles[pathname];

        // 处理 base64 编码的文件（二进制文件）
        if (typeof content === 'string' && content.startsWith('"data:')) {
          const base64String = JSON.parse(content);
          return decodeBase64Response(base64String);
        }

        // 处理文本文件
        const mimeType = getMimeType(pathname);
        const textContent = typeof content === 'string' ? JSON.parse(content) : content;

        return new Response(textContent, {
          headers: {
            'Content-Type': mimeType + '; charset=UTF-8',
            'Cache-Control': 'public, max-age=3600'
          }
        });
      }

      // 返回 404
      return new Response('<h1>404 Not Found</h1><p>The requested page could not be found.</p>', {
        status: 404,
        headers: { 'Content-Type': 'text/html; charset=UTF-8' }
      });

    } catch (error) {
      console.error('Error serving request:', error);
      return new Response('Internal Server Error', {
        status: 500,
        headers: { 'Content-Type': 'text/plain' }
      });
    }
  }
};`;

  fs.writeFileSync('worker-generated.js', workerTemplate);
  console.log('✅ Generated worker-generated.js');
  console.log('📁 Static files included:');
  Object.keys(staticFiles).forEach(path => {
    console.log('  ', path);
  });
}

// 运行构建
if (require.main === module) {
  generateWorker();
}

module.exports = { generateWorker };